package com.android.love.ui;

import java.io.IOException;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;

import org.json.JSONException;
import org.json.JSONObject;

import android.content.Intent;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.AdapterView;
import android.widget.GridView;
import android.widget.ListView;
import android.widget.TextView;

import com.android.love.R;
import com.android.love.adapter.CommentAdapter;
import com.android.love.adapter.CommentAdapter_1;
import com.android.love.net.UriHelper;
import com.android.love.util.ActivityUtil;
import com.android.love.util.FileUtil;
import com.android.love.util.LogUtil;
import com.android.love.view.GridViewWithHeaderBaseAdapter.GridItemClickListener;
import com.android.love.vo.Goods;
import com.android.love.vo.MyRequest;
import com.github.kevinsawicki.wishlist.ViewFinder;
import com.github.kevinsawicki.wishlist.ViewUtils;
import com.handmark.pulltorefresh.library.PullToRefreshBase.Mode;
import com.handmark.pulltorefresh.library.PullToRefreshBase.OnLastItemVisibleListener;
import com.handmark.pulltorefresh.library.PullToRefreshGridView;
import com.handmark.pulltorefresh.library.PullToRefreshListView;

public class ClassifyDetailActivity extends BasePageActivity implements GridItemClickListener {

    private ViewFinder classDetailFider;

    /** 商品列表 **/
    private List<Goods> goods;

    // private PullToRefreshGridView mPullToRefreshGridView;
    private PullToRefreshListView mPullToRefreshListView;

    // private GridView mGridView;
    private ListView mListView;

    // private CommentAdapter mCommentAdapter;
    // private CommentAdapter mListAdapter;
    private CommentAdapter_1 mListAdapter;

    /** 页数 **/
    private int page=1;

    /** 是否弹出加载中提示 **/
    private boolean show=true;

    /** 商品分类 **/
    private int type;

    private View footView;

    /** 筛选分类 **/
    private int detail_type=0;

    private static final int HOT=0;

    private static final int JIEGE_DOWN=1;

    private static final int JIEGE_UP=2;

    /** 排列模式(列表或grid) **/
    private int arrange_type;

    private View classDetailView;

    private boolean search;

    private String keywords;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        classDetailView=inflater.inflate(R.layout.activity_detail, null);
        setContentView(classDetailView);
        classDetailFider=new ViewFinder(classDetailView);
        process();
        setListener();
        getData();
        LogUtil.i(TAG, "onCreate");
    }

    @Override
    protected Boolean loadBottomTab() {
        // TODO Auto-generated method stub
        return false;
    }

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        LogUtil.i(TAG, "onNewIntent");
    }

    @Override
    protected void onResume() {
        mApplication.setDefaultIndex(HOME);
        super.onResume();
        LogUtil.i(TAG, "onResume");
    }

    @Override
    protected void onDestroy() {
        // TODO Auto-generated method stub
        super.onDestroy();
    }

    @Override
    public void handle(int tag, Object object) {
        super.handle(tag, object);
        switch(tag) {
            case CATALOG:
                if(footView != null)
                    footView.setVisibility(View.GONE);
                if(object != null) {
                    LogUtil.i(TAG, "success");
                    List<Goods> list_goods=(List<Goods>)object;
                    if(list_goods != null && list_goods.size() > 0) {
                        updateGoods(list_goods);
                        // for(Goods goods: list_goods) {
                        // FileUtil.saveTempFile(goods, context);
                        // }
                    } else {
                        if(search && page == 1) {
                            finish(true);
                            ActivityUtil.show(ClassifyDetailActivity.this, "没有搜索结果");
                        } else
                            ActivityUtil.show(ClassifyDetailActivity.this, "没有更多数据");
                    }
                } else {
                    if(search && page == 1) {
                        ActivityUtil.show(ClassifyDetailActivity.this, "没有搜索结果");
                        finish(true);
                    }else{
                    	page--;
                    }

                }
                // mPullToRefreshGridView.onRefreshComplete();
                mPullToRefreshListView.onRefreshComplete();
                break;

            default:
                break;
        }

    }

    private void updateGoods(List<Goods> recommends) {
        goods.addAll(recommends);
        // if (mCommentAdapter == null) {
        // // mGridView.setColumnNumber(1);
        // mCommentAdapter = new CommentAdapter(context, loader, goods, 0);
        // mGridView.setAdapter(mCommentAdapter);
        // } else {
        // mCommentAdapter.notifyDataSetChanged();
        // }
        if(mListAdapter == null) {
            // mGridView.setColumnNumber(1);
            mListAdapter=new CommentAdapter_1(context, loader, goods, 0);
            mListAdapter.setNumColumns(2);
            mListAdapter.setOnGridClickListener(this);
            mListView.setAdapter(mListAdapter);
        } else {
            mListAdapter.notifyDataSetChanged();
        }
    }

    @Override
    protected void process() {
        super.process();
        Intent intent=getCurrentIntent();
        if(intent != null) {
            search=intent.getBooleanExtra("search", false);
            if(search) {
                keywords=intent.getStringExtra("keywords");
            }
            type=intent.getIntExtra("type", 1);
        }
        arrange_type=0;
        goods=new ArrayList<Goods>();
        // mPullToRefreshGridView = (PullToRefreshGridView)
        // findViewById(R.id.detail_grid);
        mPullToRefreshListView=(PullToRefreshListView)findViewById(R.id.detail_list);
        // mGridView = mPullToRefreshGridView.getRefreshableView();
        mListView=mPullToRefreshListView.getRefreshableView();
        footView=LayoutInflater.from(context).inflate(R.layout.loading_item, null);
        TextView textView=(TextView)footView.findViewById(R.id.tv_loading);
        textView.setText("正在加载.....");
        mListView.addFooterView(footView);
        footView.setVisibility(View.GONE);
        // ViewUtils.setGone(mPullToRefreshGridView, false);
        // ViewUtils.setGone(mPullToRefreshListView, true);
        // mGridView.setColumnNumber(1);
        updateTitle(type);

    }

    @Override
    protected void getData() {
        super.getData();
        updateDetailType();
        MyRequest req=new MyRequest();
        req.authority=UriHelper.REALM_NAME;
        if(search)
            req.path=UriHelper.URL_SEARCH;
        else
            req.path=UriHelper.URL_CATALOG;
        req.paramers=generateParams(page, detail_type);
        getDataFromTask(context, CATALOG, req, goods, show, true);
    }

    @Override
    protected void setListener() {
        super.setListener();
        classDetailFider.find(R.id.iv_hot).setOnClickListener(this);
        classDetailFider.find(R.id.iv_jiage).setOnClickListener(this);
        classDetailFider.find(R.id.iv_shuaxin).setOnClickListener(this);
        classDetailFider.find(R.id.iv_top_meinv).setOnClickListener(this);
        // mPullToRefreshGridView.setMode(Mode.DISABLED);
        mPullToRefreshListView.setMode(Mode.DISABLED);
        mPullToRefreshListView.setOnLastItemVisibleListener(new OnLastItemVisibleListener() {

            @Override
            public void onLastItemVisible() {
                LogUtil.i(TAG, "OnLastItemVisibleListener....");
                if(footView != null)
                    footView.setVisibility(View.VISIBLE);
                show=false;
                page++;
                getData();
            }
        });

        // mListView.setOnItemClickListener(new
        // AdapterView.OnItemClickListener() {
        //
        // @Override
        // public void onItemClick(AdapterView<?> parent, View view,
        // int position, long id) {
        // Intent intent = new Intent(context, DetailActivity.class);
        // intent.putExtra("goods", goods.get(position));
        // startActivity(intent);
        //
        // }
        // });

        // mPullToRefreshGridView
        // .setOnLastItemVisibleListener(new OnLastItemVisibleListener() {
        //
        // @Override
        // public void onLastItemVisible() {
        // LogUtil.i(TAG, "OnLastItemVisibleListener....");
        // if (footView != null)
        // footView.setVisibility(View.VISIBLE);
        // show = false;
        // page++;
        // getData();
        // }
        // });

        // mGridView.setOnItemClickListener(new
        // AdapterView.OnItemClickListener() {
        //
        // @Override
        // public void onItemClick(AdapterView<?> parent, View view,
        // int position, long id) {
        // LogUtil.i(TAG, "position...." + position);
        // Intent intent = new Intent(context, DetailActivity.class);
        // if (position - 1 >= 0)
        // intent.putExtra("goods", goods.get(position - 1));
        // else
        // intent.putExtra("goods", goods.get(position));
        // startActivity(intent);
        //
        // }
        // });
    }

    /**
     * 得到传递的参数
     * 
     * @return
     * @throws JSONException
     * @throws IOException
     */
    public Map<String, String> generateParams(int page, int detail_type) {
        JSONObject json=new JSONObject();
        TreeMap<String, String> params=new TreeMap<String, String>();
        params.put("app_key", "android");
        if(search)
            params.put("keywords", keywords);
        else
            params.put("type", type + "");
        params.put("order", detail_type + "");
        params.put("v", "1.0");
        params.put("page", page + "");
        params.put("count", "10");
        return params;
    }

    @Override
    public void onClick(View v) {
        super.onClick(v);
        switch(v.getId()) {
            case R.id.iv_top_meinv:
                finish(true);
                break;
            case R.id.iv_hot:
                if(detail_type == HOT)
                    return;
                detail_type=HOT;
                page=1;
                show=true;
                goods.clear();
                // mCommentAdapter.notifyDataSetChanged();
                mListAdapter.notifyDataSetChanged();
                getData();
                break;
            case R.id.iv_jiage:
                if(goods != null && !goods.isEmpty()) {
                    if(detail_type == HOT || detail_type == JIEGE_DOWN)
                        detail_type=JIEGE_UP;
                    else if(detail_type == JIEGE_UP)
                        detail_type=JIEGE_DOWN;
                    page=1;
                    show=true;
                    goods.clear();
                    // mCommentAdapter.notifyDataSetChanged();
                    mListAdapter.setOnGridClickListener(ClassifyDetailActivity.this);
                    mListAdapter.notifyDataSetChanged();
                    getData();
                }
                break;
            case R.id.iv_shuaxin:
                if(arrange_type == 0) {
                    arrange_type=1;
                    classDetailFider.setDrawable(R.id.iv_shuaxin, R.drawable.btn_type_select_grid);
                    // ViewUtils.setGone(mPullToRefreshGridView, true);
                    // ViewUtils.setGone(mPullToRefreshListView, false);
                    mListAdapter=new CommentAdapter_1(context, loader, goods, 1);
                    mListAdapter.setNumColumns(1);
                    // mListAdapter.notifyDataSetChanged();
                    mListAdapter.setOnGridClickListener(ClassifyDetailActivity.this);
                    mListView.setAdapter(mListAdapter);
                    ActivityUtil.show(ClassifyDetailActivity.this, "已切换到列表模式");
                } else {
                    arrange_type=0;
                    classDetailFider.setDrawable(R.id.iv_shuaxin, R.drawable.btn_type_select_list);
                    // ViewUtils.setGone(mPullToRefreshGridView, false);
                    // ViewUtils.setGone(mPullToRefreshListView, true);
                    mListAdapter=new CommentAdapter_1(context, loader, goods, 0);
                    mListAdapter.setNumColumns(2);
                    // mListAdapter.notifyDataSetChanged();
                    mListAdapter.setOnGridClickListener(ClassifyDetailActivity.this);
                    mListView.setAdapter(mListAdapter);
                    ActivityUtil.show(ClassifyDetailActivity.this, "已切换到视图模式");

                }
                // mCommentAdapter = new CommentAdapter(context, loader, goods,
                // arrange_type);
                // mGridView.setAdapter(mCommentAdapter);
                break;

            default:
                break;
        }
    }

    /**
     * 更新筛选栏样式
     */
    private void updateDetailType() {
        switch(detail_type) {
            case HOT:
                classDetailFider.imageView(R.id.iv_hot).setBackgroundResource(R.drawable.hot_focus);
                classDetailFider.imageView(R.id.iv_jiage).setBackgroundResource(R.drawable.jiage);
                break;
            case JIEGE_DOWN:
                classDetailFider.imageView(R.id.iv_hot).setBackgroundResource(R.drawable.hot_normal);
                classDetailFider.imageView(R.id.iv_jiage).setBackgroundResource(R.drawable.jiagedown_on);
                // classDetailFider.setDrawable(R.id.iv_hot, R.drawable.hot_normal);
                // classDetailFider
                // .setDrawable(R.id.iv_jiage, R.drawable.jiagedown_on);
                break;
            case JIEGE_UP:
                classDetailFider.imageView(R.id.iv_hot).setBackgroundResource(R.drawable.hot_normal);
                classDetailFider.imageView(R.id.iv_jiage).setBackgroundResource(R.drawable.jiageup_on);
                break;

            default:
                break;
        }
    }

    public void updateTitle(int ty) {
        switch(ty) {
            case -1:
                classDetailFider.setText(R.id.top_title, "搜索");
                break;
            case 1:
                classDetailFider.setText(R.id.top_title, "情趣内衣");
                break;
            case 7:
                type=2;
                classDetailFider.setText(R.id.top_title, "情趣礼品");
                break;
            case 2:
                type=3;
                classDetailFider.setText(R.id.top_title, "计生用品");
                break;
            case 3:
                type=4;
                classDetailFider.setText(R.id.top_title, "男用器具");
                break;
            case 4:
                type=5;
                classDetailFider.setText(R.id.top_title, "女用器具");
                break;
            case 5:
                type=6;
                classDetailFider.setText(R.id.top_title, "情趣用品");
                break;
            case 6:
                type=7;
                classDetailFider.setText(R.id.top_title, "情趣家具");
                break;

            default:
                break;
        }
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if(event.getAction() == KeyEvent.ACTION_DOWN && keyCode == KeyEvent.KEYCODE_BACK) {
            finish(true);
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    @Override
    public void onGridItemClicked(View v, int position, long itemId) {
        Intent intent=new Intent(context, DetailActivity.class);
        // intent.putExtra("goods", goods.get(position));
        // startActivity(intent);
        intent.putExtra("type", 1);
        intent.putExtra("goods", (Serializable)goods);
        intent.putExtra("position", position);
        // intent.putExtra("topgoods", (Serializable)goods);
        startActivity(intent);

    }
}
